import { Injectable, Injector } from '@angular/core';
import { Overlay, OverlayConfig, OverlayRef } from '@angular/cdk/overlay';
import { ComponentPortal } from '@angular/cdk/portal';
import { Observable, Subject } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class OverlayService {
  private addSubject = new Subject<string>();

  addSubject$ = this.addSubject.asObservable();

  constructor(
      private overlay: Overlay,
  ) {
  }

  create(component: any): OverlayRef {
    let strategy = this.overlay.position().global().centerHorizontally().centerVertically();
    let overlayConfig = new OverlayConfig({hasBackdrop: false, positionStrategy: strategy});
    let overlayRef = this.overlay.create(overlayConfig);
    let injector = Injector.create({
      providers: [
        {provide: OverlayRef, useValue: overlayRef},
        {provide: Observable, useValue: this.addSubject$}],
    });
    overlayRef.attach(new ComponentPortal(component, null, injector));
    return overlayRef;
  }

  add(value: string) {
    this.addSubject.next(value);
  }
}
